package com.ustb.mongodemo;

import com.ustb.mongodemo.entity.User;
import com.ustb.mongodemo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.*;

import java.util.List;


/**
 * @author ShiZhe
 * @create 2021-06-15 10:21
 */
@SpringBootTest
public class MongoDemoApplicationTest1 {

    @Autowired
    private UserRepository userRepository;

    // 添加操作
    @Test
    public void create() {
        User user = new User();
        user.setName("lucy");
        user.setAge(18);
        user.setEmail("185125@qq.com");
        User user1 = userRepository.save(user);
        System.out.println(user1);
    }

    // 查询所有数据
    @Test
    public void findAll() {
        List<User> all = userRepository.findAll();
        System.out.println(all);
    }

    // 根据id查询
    @Test
    public void findById() {
        User user = userRepository.findById("60c84e78f95adb7e06618be7").get();
        System.out.println(user);
    }

    // 条件查询
    @Test
    public void find() {
        User user = new User();
        user.setName("lucy");
        user.setAge(18);
        Example<User> example = Example.of(user);
        List<User> all = userRepository.findAll(example);
        System.out.println(all);
    }

    // 模糊查询
    @Test
    public void findLike() {
        // 设置模糊查询匹配规则，withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)表示设置为模糊查询，withIgnoreCase(true)表示忽略大小写
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        User user = new User();
        user.setName("y");
        Example<User> example = Example.of(user,matcher);
        List<User> all = userRepository.findAll(example);
        System.out.println(all);
    }

    // 分页查询
    @Test
    public void findPage() {
        // 设置分页
        // 0表示第一页
        Pageable pageable = PageRequest.of(0, 3);
        User user = new User();
        user.setName("lucy");
        Example<User> example = Example.of(user);
        Page<User> page = userRepository.findAll(example, pageable);
        System.out.println(page);
    }

    // 修改
    @Test
    public void update() {
        User user = userRepository.findById("60c84e78f95adb7e06618be7").get();
        user.setAge(30);
        // 有id修改，无id添加
        User user1 = userRepository.save(user);
        System.out.println(user1);
    }

    // 删除
    @Test
    public void delete() {
        userRepository.deleteById("60c84e78f95adb7e06618be7");
    }
}
